<template lang="pug">
.entry-type-edit
  Dialog(
    v-model="model"
    cancel-text="取消"
    size="mini"
    :title="title"
    v-bind:onCancel="onCancel"
    v-bind:onConfirm="onConfirm"
    v-bind:onClose="onClose"
    :fullscreen="false"
    :confirmLoading="loadingMap && loadingMap['save']"
  )
    mt-form(v-bind="editBasicFormProps",ref="basicFormRef")

</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type EditFormProps,
  useNotify,
  Form,
  Dialog,
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import type { EntryTypeEntity } from "@scmt/api-pacs-entry-type";
import { useApi } from "@scmt/core-api";

//添加 Props属性
const props = defineProps({
  selectItem: Object,
});
const model = defineModel({
  default: false,
});

//添加事件
const emit = defineEmits(["handleQuery"]);
const $api = useApi();
const $notify = useNotify();
const editingObj = ref<null | EntryTypeEntity>(null);
const title = ref("");
//弹框点击确认事件
//关闭弹框
const onCancel = () => {
  model.value = false;
};
//取消
const onClose = () => {
  model.value = false;
};
const editBasicFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "parentName",
      label: "当前选择",
      required: true,
      disabled: true,
    },
    {
      prop: "name",
      label: "术语名称",
      required: true,
      options: {
        type: "textarea",
      },
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    loading: loadingMap.save,
    size: "mini",
    columns: 1,
  };

  return editProps;
});
const basicFormRef = ref<null | InstanceType<typeof Form>>(null);
//校验
const validate = (
  callback?: (valid: boolean, model: any) => Promise<void> | void
) => {
  //@ts-ignore
  basicFormRef.value?.validate((valid) => {
    typeof callback === "function" && callback(valid, editingObj.value);
  });
};
const { request, loadingMap } = useRequest({
  save: (entity: EntryTypeEntity) => {
    return $api.pacs.entryType.save(entity).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;
      model.value = false;
      emit("handleQuery");
    });
  },
});
//弹框点击确认事件
const onConfirm = () => {
  if (props.selectItem) {
    validate((valid, model) => {
      if (valid && model) {
        //@ts-ignore
        request("save", editingObj.value);
      } else {
        $notify.warning("请按照提示填写完整!!");
      }
    });
  }
};
watch(
  () => model.value,
  (item) => {
    title.value = "新增分类信息";
    editingObj.value = $api.pacs.entryType.$$createEntity(props.selectItem);
    if (item) {
      if (props.selectItem && props.selectItem.id) {
        title.value = "编辑分类信息";
      }
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
